
from functools import wraps
from flask import session, redirect, url_for, jsonify, request


def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user_id' not in session:

            if request.path.startswith('/api/'):
                return jsonify({
                    'error': '请先登录',
                    'success': False
                }), 401

            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function


def admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user_id' not in session:
            if request.path.startswith('/api/'):
                return jsonify({
                    'error': '请先登录',
                    'success': False
                }), 401
            return redirect(url_for('login'))

        if session.get('role') != 'admin':
            if request.path.startswith('/api/'):
                return jsonify({
                    'error': '需要管理员权限',
                    'success': False
                }), 403
            return jsonify({'error': '需要管理员权限'}), 403

        return f(*args, **kwargs)
    return decorated_function


def get_current_user():
    if 'user_id' in session:
        return {
            'id': session.get('user_id'),
            'username': session.get('username'),
            'role': session.get('role'),
            'email': session.get('email')
        }
    return None


def set_user_session(user_data):
    session['user_id'] = user_data['id']
    session['username'] = user_data['username']
    session['role'] = user_data['role']
    session['email'] = user_data['email']


def clear_user_session():
    session.pop('user_id', None)
    session.pop('username', None)
    session.pop('role', None)
    session.pop('email', None)
